#include <iostream>
#include <vector>

using namespace std;
class Solution {
public:
    int maxProfit(vector<int>& p) {
        int n = p.size();
        vector<vector<int>> f(n, vector<int>(3));
        vector<vector<int>> g(n, vector<int>(3));
        for (int i = 1; i < 3; ++i)
        {
            f[0][i] = -0x3f3f3f3f;
            g[0][i] = -0x3f3f3f3f;
        }
        f[0][0] = -p[0]; g[0][0] = 0;
        for (int i = 1; i < n; ++i)
        {
            for (int j = 0; j <= 2; ++j)
            {
                f[i][j] = max(f[i - 1][j], g[i - 1][j] - p[i]);
                if (j >= 1)
                    g[i][j] = max(g[i - 1][j], f[i - 1][j - 1] + p[i]);
                else
                    g[i][j] = g[i - 1][j];
            }
        }
        int ret = 0;
        for (int i = 0; i <= 2; ++i)
        {
            if (ret < g[n - 1][i])
                ret = g[n - 1][i];
        }
        return ret;
    }
};